<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="倍增与稀疏表（ST表） 倍增思想的核心在于通过预处理每个状态的跳跃步长（如2的幂次），将线性时间的操作优化为对数时间。其关键在于构建一个跳跃表，每个位置存储跳跃不同\(2^k\)步后的结果。对于多次跳跃问题，将总步数分解为若干2的幂次之和，逐次跳跃即可高效求解。">
<meta property="og:type" content="article">
<meta property="og:title" content="25.倍增与稀疏表">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="倍增与稀疏表（ST表） 倍增思想的核心在于通过预处理每个状态的跳跃步长（如2的幂次），将线性时间的操作优化为对数时间。其关键在于构建一个跳跃表，每个位置存储跳跃不同\(2^k\)步后的结果。对于多次跳跃问题，将总步数分解为若干2的幂次之和，逐次跳跃即可高效求解。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult1.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult2.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult3.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult4.svg">
<meta property="article:published_time" content="2025-04-05T14:41:40.000Z">
<meta property="article:modified_time" content="2025-04-10T04:41:18.563Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult1.svg">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/","path":"2025-04-05-25-倍增与稀疏表/","title":"25.倍增与稀疏表"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>25.倍增与稀疏表 | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8st%E8%A1%A8"><span class="nav-number">1.</span> <span class="nav-text">倍增与稀疏表（ST表）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%80%8D%E5%A2%9E%E6%80%9D%E6%83%B3"><span class="nav-number">1.1.</span> <span class="nav-text">倍增思想</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E5%8F%98%E5%8C%96%E7%9A%84%E6%95%B0"><span class="nav-number">1.1.1.</span> <span class="nav-text">例：变化的数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%A8%80%E7%96%8F%E8%A1%A8"><span class="nav-number">1.2.</span> <span class="nav-text">稀疏表</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E5%A4%9A%E6%AC%A1%E6%9F%A5%E8%AF%A2%E5%8C%BA%E9%97%B4%E6%9C%80%E5%A4%A7%E5%80%BC"><span class="nav-number">1.2.1.</span> <span class="nav-text">例：多次查询区间最大值</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="25.倍增与稀疏表 | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          25.倍增与稀疏表
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-04-05 22:41:40" itemprop="dateCreated datePublished" datetime="2025-04-05T22:41:40+08:00">2025-04-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-04-10 12:41:18" itemprop="dateModified" datetime="2025-04-10T12:41:18+08:00">2025-04-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="倍增与稀疏表st表">倍增与稀疏表（ST表）</h1>
<p>倍增思想的核心在于通过预处理每个状态的跳跃步长（如2的幂次），将线性时间的操作优化为对数时间。其关键在于构建一个跳跃表，每个位置存储跳跃不同<span
class="math inline">\(2^k\)</span>步后的结果。对于多次跳跃问题，将总步数分解为若干2的幂次之和，逐次跳跃即可高效求解。</p>
<span id="more"></span>
<h2 id="倍增思想">倍增思想</h2>
<p>纸币有1元、5元、10元、50元、100元的面额，用于方便地凑成任意金额。</p>
<p>在编程思维中，<span class="math inline">\(2^0, 2^1, 2^2, \dots
2^k\)</span> 可以方便地凑成任意 <span
class="math inline">\(2^{k+1}\)</span>
以内的数（更大的也能凑，但是没那么方便快捷），甚至每个额度只需要出现一次。</p>
<p>随便考虑一个数： <span
class="math inline">\(12\)</span>，它的二进制形式是
<code>1100</code>，二进制的每一位都对应一个<span
class="math inline">\(2^{x}\)</span>，即可以由若干个不重复的<span
class="math inline">\(2^{x}\)</span>凑成。每个整数都可以表达成二进制，所以以上结论显然。</p>
<p>在一些问题中，解存在<strong>某种特定关系</strong>，或许能允许我们<strong>以相对较小的代价</strong>预处理出变量（或偏移量）为
<span class="math inline">\(2^0, 2^1, 2^2, \dots 2^k\)</span>
的结果，从而快速地拼凑任意变量（或偏移量）对应的结果，这就是<strong>倍增思想</strong>。</p>
<h3 id="例变化的数">例：变化的数</h3>
<p>一个数<span class="math inline">\(a\)</span>，每变化一次，就增加
<span class="math inline">\(\lfloor \max (|sin(a)|, |cos(a)|) * 20
\rfloor\)</span>.</p>
<p>用C语言可以这样完成变化：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">Nexa</span><span class="params">(<span class="type">int</span> a)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + (<span class="type">int</span>)(std::<span class="built_in">max</span>(<span class="built_in">fabs</span>(<span class="built_in">sin</span>(a)), <span class="built_in">fabs</span>(<span class="built_in">cos</span>(a))) * <span class="number">20</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>求它变化 <span class="math inline">\(m\)</span> 次的值.</p>
<p>第一行数据组数 <span class="math inline">\(1 \leq t \leq 5 *
10^{4}\)</span>，接下来 <span class="math inline">\(t\)</span>
行数据，每行 <span class="math inline">\(1 \leq a, m \leq 5 *
10^{4}\)</span> 表示将 <span class="math inline">\(a\)</span> 变化 <span
class="math inline">\(m\)</span> 次.</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">5</span><br><span class="line">8 15</span><br><span class="line">8 9</span><br><span class="line">3 7</span><br><span class="line">11 10</span><br><span class="line">17 14</span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">264</span><br><span class="line">162</span><br><span class="line">133</span><br><span class="line">184</span><br><span class="line">256</span><br></pre></td></tr></table></figure>
<p>如果<span class="math inline">\(m\)</span>步慢慢模拟，<span
class="math inline">\(t\)</span>组数据每组<span
class="math inline">\(m\)</span>步就超时了。</p>
<p>如果有每个点走<span
class="math inline">\(2^{0},2^{1},\dots\)</span>步能到达的地方的信息，那么走<span
class="math inline">\(m\)</span>步就会减少到走 <span
class="math inline">\(log_{2}m\)</span>步。</p>
<img src="/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult1.svg" class="">
<p>这不仅需要知道第 1 个点的各<span
class="math inline">\(2^i\)</span>步到达位置，而是要知道每一个点的各个<span
class="math inline">\(2^i\)</span>步到达的位置</p>
<p>如下图，一个点的绿、蓝、红、紫线路对应<span
class="math inline">\(2^{0},2^{1},,2^{2},2^{3}\)</span> 步</p>
<img src="/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult2.svg" class="">
<p>如果想从起点走 6 步，就先走 1
步红线，到达一个点，然后需要知道这个点的 1 步蓝线，到达目的地。</p>
<img src="/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult3.svg" class="">
<p>只要知道<strong>所有点的所有<span
class="math inline">\(2^{0},2^{1},,2^{2},\dots\)</span></strong>
步能到达的位置，就可以在 <span
class="math inline">\(log_{2}m\)</span>时间快速计算从任意点出发走<span
class="math inline">\(m\)</span>步到达的位置。</p>
<img src="/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/mult4.svg" class="">
<p>预处理这个信息也有技巧：</p>
<ul>
<li>从每个点出发走 <span class="math inline">\(1\)</span>
步能到的地方，用一个循环处理出来；</li>
<li>从每个点出发走 <span class="math inline">\(2\)</span>
步能到的地方，可以由它走<span
class="math inline">\(1\)</span>步到某个点，该点再走<span
class="math inline">\(1\)</span>步到达，而每个点的<span
class="math inline">\(1\)</span>步到达位置此时已知；</li>
<li>从每个点出发走 <span class="math inline">\(4\)</span>
步能到的地方，可以由它走<span
class="math inline">\(2\)</span>步到某个点，该点再走<span
class="math inline">\(2\)</span>步到达，而每个点的<span
class="math inline">\(2\)</span>步到达位置此时已知；</li>
<li>……</li>
</ul>
<p>以上每一步都遍历一遍所有点，共遍历 <span
class="math inline">\(k\)</span> 次，<span
class="math inline">\(k\)</span> 就是需要预处理的最大的 <span
class="math inline">\(2^{k}\)</span> 步的 <span
class="math inline">\(k\)</span>，假设点个数是 <span
class="math inline">\(n\)</span>，<span class="math inline">\(2^k\approx
n\)</span>，所以这个预处理过程是<span
class="math inline">\(O(nlogn)\)</span>的。</p>
<p>回到题目，一个数<span
class="math inline">\(a\)</span>，每变化一次，就增加 <span
class="math inline">\(\lfloor \max (|sin(a)|, |cos(a)|) * 20
\rfloor\)</span>，它每次至多增加<span
class="math inline">\(20\)</span>，由于<span class="math inline">\(1
\leq a, m \leq 5 * 10^{4}\)</span>，那么这道题最大范围就是 <span
class="math inline">\(5 * 10^4 + 20 * 5 * 10^4 \approx 10^6\)</span></p>
<p>预处理这样做</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">const</span> <span class="type">int</span> maxa = <span class="number">2e5</span> + <span class="number">1e4</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxmt = <span class="number">22</span>;</span><br><span class="line"><span class="type">int</span> mt[maxa][maxmt];    <span class="comment">// maxa 表示起点的可能性数， maxmt 表示最多处理到 2^maxmt 步</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">InitMt</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt; maxa; j ++) &#123;</span><br><span class="line">        mt[j][<span class="number">0</span>] = <span class="built_in">Nexa</span>(j);     <span class="comment">// 初始化走 1 步（即 2^0 步）的值</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt; maxmt; i ++) &#123;       <span class="comment">// 枚举步长，i 表示 2^i 步</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt; maxa; j ++) &#123;    <span class="comment">// 枚举起点</span></span><br><span class="line">            <span class="comment">// 利用 2^&#123;i-1&#125; 的信息推算每个 j 位置走 2^i 步的值</span></span><br><span class="line">            <span class="keyword">if</span>(mt[j][i - <span class="number">1</span>] &gt;= maxa) &#123;</span><br><span class="line">                <span class="keyword">break</span>;  <span class="comment">// 超出题目可能的范围，这部分不用计算</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 位置 j 出发走 2^i 步到的位置，可以从 mt[j][i - 1] 出发走 2^&#123;i-1&#125; 步到达</span></span><br><span class="line">            <span class="comment">// mt[*][i - 1] 已由上一轮循环计算好了</span></span><br><span class="line">            mt[j][i] = mt[mt[j][i - <span class="number">1</span>]][i - <span class="number">1</span>];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么 <span class="math inline">\(a\)</span> 出发走 <span
class="math inline">\(m\)</span> 步，就可以拆解成走 <span
class="math inline">\(m\)</span> 的各个二进制位对应的步数。</p>
<p>比如 <span class="math inline">\(m =
7\)</span>，它的最高二进制位就是第 <span class="math inline">\(\lfloor
log_{2}7 \rfloor=2\)</span> 位，第一步就可以走 <span
class="math inline">\(2^2\)</span> 步，对应预处理的表就是
<code>mt[a][2]</code> ，表示从 <span class="math inline">\(a\)</span>
出发走 <span class="math inline">\(2^{2} = 4\)</span> 步到达的位置。</p>
<p>更新位置<code>a = mt[a][2]</code>，准备走下一步，那么还剩下 <span
class="math inline">\(7 - 2^2 = 3\)</span>
步，从刚到达的位置出发，进行下一轮计算。</p>
<p>二进制计算有一些加速的 <code>__builtin_***</code>
函数可以用，这里可以代替 <code>(int)log2(x)</code> 得到更好性能。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">Fastlog</span><span class="params">(<span class="type">int</span> x)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// log2函数较慢，利用 int 二进制位数高效地计算 (int)log2(x)</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">31</span> - __builtin_clz(x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">while</span>(m) &#123;</span><br><span class="line">    <span class="type">int</span> lg = <span class="built_in">Fastlog</span>(m);    <span class="comment">// 找距离 m 最近的 2^&#123;lg&#125; 的 lg</span></span><br><span class="line">    a = mt[a][lg];          <span class="comment">// 走 2^&#123;lg&#125; 步</span></span><br><span class="line">    m -= <span class="number">1</span> &lt;&lt; lg;           <span class="comment">// 减去走过的步数，位运算 1&lt;&lt;lg 就是2^&#123;lg&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>完整代码如下</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 变化的数</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstring&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdlib&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cmath&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxa = <span class="number">2e5</span> + <span class="number">1e4</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxmt = <span class="number">22</span>;</span><br><span class="line"><span class="type">int</span> mt[maxa][maxmt];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">Nexa</span><span class="params">(<span class="type">int</span> a)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + (<span class="type">int</span>)(std::<span class="built_in">max</span>(<span class="built_in">fabs</span>(<span class="built_in">sin</span>(a)), <span class="built_in">fabs</span>(<span class="built_in">cos</span>(a))) * <span class="number">20</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">InitMt</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt; maxa; j ++) &#123;</span><br><span class="line">        mt[j][<span class="number">0</span>] = <span class="built_in">Nexa</span>(j);     <span class="comment">// 初始化走 1 步（即 2^0 步）的值</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt; maxmt; i ++) &#123;       <span class="comment">// 枚举步长，i 表示 2^i 步</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt; maxa; j ++) &#123;    <span class="comment">// 枚举起点</span></span><br><span class="line">            <span class="comment">// 利用 2^&#123;i-1&#125; 的信息推算每个 j 位置走 2^i 步的值</span></span><br><span class="line">            <span class="keyword">if</span>(mt[j][i - <span class="number">1</span>] &gt;= maxa) &#123;</span><br><span class="line">                <span class="keyword">break</span>;  <span class="comment">// 超出题目可能的范围，这部分不用计算</span></span><br><span class="line">            &#125;</span><br><span class="line">            mt[j][i] = mt[mt[j][i - <span class="number">1</span>]][i - <span class="number">1</span>];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">Fastlog</span><span class="params">(<span class="type">int</span> x)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// log2函数较慢，利用 int 二进制位数高效地计算 (int)log2(x)</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">31</span> - __builtin_clz(x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="type">int</span> t, a, m;</span><br><span class="line">    <span class="built_in">InitMt</span>();</span><br><span class="line">    <span class="keyword">for</span>(<span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;t); t --; ) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;a, &amp;m);</span><br><span class="line">        <span class="keyword">while</span>(m) &#123;</span><br><span class="line">            <span class="type">int</span> lg = <span class="built_in">Fastlog</span>(m);    <span class="comment">// 找距离 m 最近的 2^&#123;lg&#125; 的 lg</span></span><br><span class="line">            a = mt[a][lg];          <span class="comment">// 走 2^&#123;lg&#125; 步</span></span><br><span class="line">            m -= <span class="number">1</span> &lt;&lt; lg;           <span class="comment">// 减去走过的步数，位运算 1&lt;&lt;lg 就是2^&#123;lg&#125;</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, a);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="稀疏表">稀疏表</h2>
<p>稀疏表用于解决<strong>可重复贡献问题</strong>。</p>
<p>对于 <span class="math inline">\(a&lt;b\)</span>， <span
class="math inline">\([l, b]\)</span>区间、<span
class="math inline">\([a, r]\)</span>区间以及<span
class="math inline">\([l, r]\)</span> 区间的一些计算：</p>
<ul>
<li>能重复贡献示例：区间最大值，<span class="math inline">\([l,
b]\)</span> 的最大值与 <span class="math inline">\([a, r]\)</span>
最大值较大的那个同时也是 <span class="math inline">\([l,r]\)</span>
的最大值， <span class="math inline">\([a,b]\)</span>
这个区间在最大值问题上就能重复贡献。</li>
<li>不能重复贡献示例： <span class="math inline">\([l, b]\)</span>
的和与 <span class="math inline">\([a, r]\)</span> 的和相加，不等于
<span class="math inline">\([l, r]\)</span>
的和，所以区间和就不能重复贡献。</li>
</ul>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">                        [a,r] </span><br><span class="line">             /-------------^-------------\</span><br><span class="line">l            a            b               r</span><br><span class="line">-------------------------------------------</span><br><span class="line">\___________ ____________/</span><br><span class="line">            V</span><br><span class="line">          [l,b]</span><br></pre></td></tr></table></figure>
<p>区间最大/最小值（Range Maximum/Minimum Query,
RMQ）是典型的可重复贡献问题。</p>
<p>这个问题可以用倍增思想加速查询，预处理好每个点作为起点，它加<span
class="math inline">\(2^0, 2^{1},
2^{2},\dots\)</span>为终点的区间解，那么对于任意 <span
class="math inline">\([l, r]\)</span> 的查询，设 <span
class="math inline">\(b\)</span> 为 <span class="math inline">\(b = l +
2^{k} &lt;= r\)</span> 能达到的最大值， <span
class="math inline">\(a\)</span> 为 <span class="math inline">\(a +
2^{k} = r\)</span> 的值，那么 <span class="math inline">\([l,
b]\)</span> 和 <span class="math inline">\([a, r]\)</span> 就是 <span
class="math inline">\([l, l + 2^{k}]\)</span> 和 <span
class="math inline">\([r - 2^{k},
r]\)</span>，只要这个问题可重复贡献，这两个预处理过的答案合起来就是
<span class="math inline">\([l, r]\)</span> 的解。</p>
<p>预处理的过程也是倍增思想来。</p>
<h3 id="例多次查询区间最大值">例：多次查询区间最大值</h3>
<p>给定一个长度为 <span class="math inline">\(N\)</span> 的数列，和
<span class="math inline">\(M\)</span>
次询问，求出每一次询问的区间内数字的最大值。</p>
<p>输入</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">8</span> <span class="number">8</span></span><br><span class="line"><span class="number">9</span> <span class="number">3</span> <span class="number">1</span> <span class="number">7</span> <span class="number">5</span> <span class="number">6</span> <span class="number">0</span> <span class="number">8</span></span><br><span class="line"><span class="number">1</span> <span class="number">6</span></span><br><span class="line"><span class="number">1</span> <span class="number">5</span></span><br><span class="line"><span class="number">2</span> <span class="number">7</span></span><br><span class="line"><span class="number">2</span> <span class="number">6</span></span><br><span class="line"><span class="number">1</span> <span class="number">8</span></span><br><span class="line"><span class="number">4</span> <span class="number">8</span></span><br><span class="line"><span class="number">3</span> <span class="number">7</span></span><br><span class="line"><span class="number">1</span> <span class="number">8</span></span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">9</span></span><br><span class="line"><span class="number">9</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line"><span class="number">9</span></span><br><span class="line"><span class="number">8</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line"><span class="number">9</span></span><br></pre></td></tr></table></figure>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstring&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cmath&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">1e5</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">int</span> n, m, a[maxn], st[maxn][<span class="number">22</span>];   <span class="comment">// 起点最大 maxn，预处理到  maxn + 2^&#123;20&#125;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">InitSt</span><span class="params">(<span class="type">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt;= n; j ++) &#123;</span><br><span class="line">        st[j][<span class="number">0</span>] = a[j];    <span class="comment">// 左闭右开区间理解， [j, j + 1) 就是长为 1 的区间</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= <span class="number">22</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt;= n - (<span class="number">1</span> &lt;&lt; (i - <span class="number">1</span>)); j ++) &#123;</span><br><span class="line">            <span class="comment">// [j, j + 2^&#123;i-1&#125;) 与 [j + 2^&#123;i-1&#125;, j + 2^&#123;i&#125;) 合并 得到 [j, j + 2^&#123;i&#125;]</span></span><br><span class="line">            st[j][i] = std::<span class="built_in">max</span>(st[j][i - <span class="number">1</span>], st[j + (<span class="number">1</span> &lt;&lt; (i - <span class="number">1</span>))][i - <span class="number">1</span>]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">Fastlog</span><span class="params">(<span class="type">int</span> x)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">31</span> - __builtin_clz(x);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">Query</span><span class="params">(<span class="type">int</span> l, <span class="type">int</span> r)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 求左闭右开区间 [l, r)</span></span><br><span class="line">    <span class="type">int</span> k = <span class="built_in">Fastlog</span>(r - l);</span><br><span class="line">    <span class="keyword">return</span> std::<span class="built_in">max</span>(st[l][k], st[r - (<span class="number">1</span> &lt;&lt; k)][k]);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;n, &amp;m);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= n; i++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">InitSt</span>(n);</span><br><span class="line">    <span class="keyword">while</span>(m--) &#123;</span><br><span class="line">        <span class="type">int</span> l, r;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;l, &amp;r);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, <span class="built_in">Query</span>(l, r + <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-04-05-24-%E5%88%86%E5%9D%97/" rel="prev" title="24.分块">
                  <i class="fa fa-angle-left"></i> 24.分块
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/" rel="next" title="26.动态规划入门">
                  26.动态规划入门 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
